package com.blog.service.impl;

import com.blog.entity.Blog;
import com.blog.entity.BlogType;
import com.blog.entity.Blogger;
import com.blog.entity.Link;
import com.blog.service.BlogService;
import com.blog.service.BlogTypeService;
import com.blog.service.BloggerService;
import com.blog.service.LinkService;
import com.blog.util.Const;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.List;



/**
 * @Author SunBingRui
 * @Date 2020/5/20 18:11
 */
@Component
public class InitComponent implements ServletContextListener, ApplicationContextAware {

    private static ApplicationContext applicationContext;//设置为static，类加载时就一直存在

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override//初始化上下文
    public void contextInitialized(ServletContextEvent servletContextEvent) {

        ServletContext application = servletContextEvent.getServletContext();
        BlogService blogService = (BlogService) applicationContext.getBean("blogService");
        BloggerService bloggerService = (BloggerService) applicationContext.getBean("bloggerService");

        //博主信息
        Blogger blogger = bloggerService.find();
        blogger.setPassword(null);
        application.setAttribute(Const.BLOGGER, blogger);//放在application域

        //博客类别
        BlogTypeService blogTypeService = (BlogTypeService) applicationContext.getBean("blogTypeService");
        List<BlogType> blogTypeCountList = blogTypeService.countList();
        application.setAttribute(Const.BLOG_blogTypeCountList, blogTypeCountList);//把博客标签放在application域

        //按年月分类的博客数量统计
        List<Blog> blogCountList = blogService.countList();
        application.setAttribute(Const.BLOG_COUNT_LIST, blogCountList);//放在application域

        //阅读排行统计
        List<Blog> blogReadCountList = blogService.countReadList();
        application.setAttribute(Const.BLOG_blogReadCountList, blogReadCountList);

        //点赞排行
        List<Blog> blogUpHitCountList = blogService.countUpHitList();
        application.setAttribute(Const.BLOG_blogUpHitCountList, blogUpHitCountList);

        //发帖排行榜
        List<Blogger> postBlogCountList = bloggerService.postBlogCountList();
        application.setAttribute(Const.BLOG_postBlogCountList,postBlogCountList);

        //友情链接
        LinkService linkService = (LinkService) applicationContext.getBean("linkService");
        List<Link> linkList = linkService.list(null);
        application.setAttribute(Const.LINK_LIST, linkList);//放在application域
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }

}
